package 多线程.批处理任务工具;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @
 * @date 2025/06/30
 */
@Configuration
public class ThreadPoolConfig {

    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    /**
     * ThreadPoolTaskExecutor 是 Spring 包装的线程池，容器关闭回自动关闭线程池
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();

        threadPool.setCorePoolSize(threadPoolProperties.getCorePoolSize());

        threadPool.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());

        threadPool.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());

        threadPool.setThreadNamePrefix("spring默认线程池-");

        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 任务都完成再关闭线程池
        threadPool.setWaitForTasksToCompleteOnShutdown(true);

        threadPool.initialize();

        return threadPool;
    }


}
